<template>
  <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm" status-icon>
    <el-row>
      <el-col :span="8">
        <el-form-item label="推荐单位" prop="recommendUnit">
          <popup-tree-input :data="orgAllList" :props="deptForm.popupTreeProps" :prop="deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : ruleForm.recommendUnit
                        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue" />
          <!-- <SelectOption :selectValue="ruleForm.recommendUnit" :options="options.unitList" @change-value="changeValue">
          </SelectOption> -->
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="团队名称" prop="teamName">
          <el-input placeholder="如果关联对象自动带出，可编辑" v-model="ruleForm.teamName" style="width: 250px" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="团队负责人" prop="teamCharge">
          <!-- <SelectOption :selectValue="ruleForm.teamCharge" :options="options.userAllList" @change-value="changeValue1">
          </SelectOption> -->
          <user-list-modal
            v-model="ruleForm.teamCharge"
            @update:modelValue="changeValue1"
            :default-users="[]"
            :multiple="false"
            :devType="'platform'"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="单位联系人" prop="unitContact">
          <!-- <SelectOption :selectValue="ruleForm.unitContact" :options="options.userAllList" @change-value="changeValue2">
          </SelectOption> -->
          <user-list-modal
            v-model="ruleForm.unitContact"
            @update:modelValue="changeValue2"
            :default-users="[]"
            :multiple="false"
            :devType="'platform'"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="联系电话" prop="unitContactRel">
          <el-input placeholder="请输入" v-model="ruleForm.unitContactRel" style="width: 250px" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="电子邮箱" prop="unitContactEmail">
          <el-input placeholder="请输入" v-model="ruleForm.unitContactEmail" style="width: 250px" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-form-item style="width: 100%" label="主要完成人" prop="mainCompletePersons">
      <div class="selectLabel">
        <el-tag v-for="tag in callPerson" :key="tag.id" class="mx-1" closable @close="handleClosePerson(tag)">
          {{ tag.username }}
        </el-tag>
      </div>
      <span class="addLabel" @click="addPersonBox">添加人员</span>
    </el-form-item>

      <el-form-item label="团队简介" prop="shortIntroduction">
        <el-input :style="{ width: '680px' }" v-model="ruleForm.shortIntroduction" :autosize="{ minRows: 2, maxRows: 6 }"
          type="textarea"
          placeholder="优秀科技团队单位简介，科技发展研究领域与中咨集团发展战略的吻合性、主要科学技 术成就、技术创新、获奖情况、科研成果应用推广情况、经济效益情况(限 3000 字以 内)。" />
      </el-form-item>

    </el-row>
  </el-form>

  <el-dialog v-model="data.addPerson" append-to-body width="60%" top="10vh" :show-close="false"
    :close-on-click-modal="false">
    <template #title>
      <el-tabs v-model="data.activeName" class="demo-tabs">
        <el-tab-pane label="员工列表" name="first">
          <div>
            <el-row>
              <el-col :span="24" align="right">
                <el-input v-model="data.params.name" placeholder="姓名" style="width: 150px; margin-right: 15px" />
                <SelectOption :options="options.unitList" style="width: 200px;margin-right: 15px;" :placeholder="'归属单位'"
                  @change-value="changeValueUnit">
                </SelectOption>
                <el-button class="ordinary" @click="search()">搜索</el-button>
                <Table :tableArr="data.userList" :pagination="data.page" :columns="data.columns" :operate="true"
                  @delectTable="delectIds" @selectItem="selectItemFn" :total="data.page.total">
                </Table>
              </el-col>
            </el-row>

          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closePersonbox">关闭</el-button>
        <el-button type="primary" @click="save()">选择</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import { getUserList } from '@/views/science/api/common'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { computed, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'

export default {
  components: {
    SelectOption,
    Table,
    UserListModal,
    PopupTreeInput
  },
  emits: {
    valueFlag: null,
  },
  props:{
    orgAllList: {
      type: Array,
      required: true,
    },
  },
  setup(props, { emit }) {
    const store = useStore() // 获取vuex的数据
    const labelPosition = ref('right')  // 表单label位置

    const deptForm = {
      parentId: 0,
      parentName: '',
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },
    }

    const data = reactive({
      activeName: ref('first'),  // 弹窗中的tab切换
      addPerson: false,
      columns: tableData.userList,
      page: { page: 1, limit: 10, total: 0 },
      params: {
        current: 1,
        size: 10,
        name: "",
        unitOrg: ""
      },
      ids: '',
      userList: [],

      innerValue: '',
      outsideValue: '',
    })

    // 弹窗中下拉选择
    const options = reactive({
      unitList: computed(() => store.state.technologyStrength.orgAllList),
      userAllList: computed(() => store.state.technologyStrength.userAllList),
    })

    const ruleForm = reactive(store.state.technologyStrength.groupINFO)

    watch(ruleForm, (newValue, oldValue) => {
      console.log("form值改变了", ruleForm)
      store.commit('technologyStrength/getgroupINFO', { ...ruleForm })
    });

    const changeValue = (item) => {
      ruleForm.recommendUnit = item.name
      ruleForm.recommendUnitId = item.id
    }
    const changeValue1 = (item) => {
      ruleForm.teamCharge = item.cname
      ruleForm.teamChargeId = item.userId
    }
    const changeValue2 = (item) => {
      ruleForm.unitContact = item.cname
      ruleForm.unitContactId = item.userId
    }

    //分页获取人员列表
    const getUseList = async () => {
      const res = await getUserList(data.params)
      data.userList = res.data.data.records
      data.page.total = res.data.data.total
    }

    const changeValueUnit = (item) => {
      data.params.unitOrg = item.id
    }

    const search = () => {
      data.page.page = 1
      getUseList()
    }

    const delectIds = (ids) => {
      data.ids = ids
    }

    const arr0 = ref(ruleForm.mainCompletePersons ? ruleForm.mainCompletePersons.split(',') : [])
    const arr1 = ref(ruleForm.mainCompletePersonIds ? ruleForm.mainCompletePersonIds.split(',') : [])
    let arr2: any = []
    arr0.value.map((item, index) => {
      const obj = {
        username: item,
        userId: arr1.value[index]
      }
      arr2.push(obj)
    })

    const callPerson: any = ref([...arr2])
    const person: any = ref([])

    const selectItemFn = (item) => {
      item.filter(
        (item, index) => {
          const obj = {
            username: item.cname,
            userId: item.userId
          }
          if (JSON.stringify(person.value).indexOf(JSON.stringify(obj)) == -1) person.value.push(obj);
        }
      )
    }


    const addPersonBox = () => {
      data.userList = []
      getUseList()
      data.addPerson = true
    }

    const handleClosePerson = (tag) => {
      callPerson.value.splice(callPerson.value.indexOf(tag), 1)
      handleSelectPerson(callPerson)
    }

    const closePersonbox = () => {
      data.addPerson = false
      person.value = []
    }

    const save = () => {
      data.addPerson = false
      person.value.filter(
        (item, index) => {
          console.log(JSON.stringify(callPerson.value).indexOf(JSON.stringify(item)))
          if (JSON.stringify(callPerson.value).indexOf(JSON.stringify(item)) == -1) callPerson.value.push(item);
        }
      )
      person.value = []
      handleSelectPerson(callPerson)
    }

    const arrname: any = reactive([])
    const arrid: any = reactive([])
    const handleSelectPerson = (val) => {
      val.value.map((item) => {
        if (arrname.indexOf(item.username) == -1) arrname.push(item.username)
        if (arrid.indexOf(item.userId) == -1) arrid.push(item.userId)
      })
      ruleForm.mainCompletePersons = arrname.join(',')
      ruleForm.mainCompletePersonIds = arrid.join(',')
    }
    //手机号码校验
    var checkPhone = (rule, value, callback) => {
        if (!value) {
                return callback(new Error("手机号不能为空"));
        } else {
            const reg = /^1[3-9][0-9]\d{8}$/;
            // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
            if (reg.test(value)) {
                    callback();
            } else {
                    // 具体错误信息没有提示
                    return callback(new Error("请输入正确的手机号"));
            }
        }
    };
    //邮箱校验
    var checkEmail = (rule, value, callback) => {
        if (!value) {
                return callback(new Error("请输入电子邮箱"));
        } else {
            const reg = /^([a-zA-Z]|[0-9])(\w|\-|\.)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
            if (reg.test(value)) {
                    callback();
            } else {
                    // 具体错误信息没有提示
                    return callback(new Error("请输入正确的电子邮箱"));
            }
        }
    };
    // 新增
    const rules = reactive({

      recommendUnit: [
        { required: true, message: '请选择推荐单位', trigger: 'change', },
      ],
      teamName: [
        { required: true, message: '输入团队名称', trigger: 'blur', },
      ],
      teamCharge: [
        { required: true, message: '请选择团队负责人', trigger: 'change', },
      ],
      unitContact: [
        { required: true, message: '请输入单位联系人', trigger: 'change', },
      ],
      unitContactRel: [
        { validator: checkPhone, trigger: "blur" },
        { min: 11, message: "手机号不足11位", trigger: "blur" },
        { required: true,  trigger: 'blur', },
      ],
      unitContactEmail: [
        { validator: checkEmail, trigger: "blur" },
        { required: true, message: '请输入电子邮箱', trigger: 'blur', },
      ],
      mainCompletePersons: [
        { required: true, message: '请选择主要完成人', trigger: 'blur' },
      ],
      shortIntroduction: [
        { required: true, message: '请输入团队简介', trigger: 'change', },
      ],
    })


    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('valueFlag', true)
        } else {
          emit('valueFlag', false)
        }
      })
    }

    return {
      open,
      submitForm,
      ruleForm,
      rules,
      ruleFormRef,
      labelPosition,
      data,
      options,
      save,

      changeValue,
      changeValue1,
      changeValue2,

      callPerson,
      search,
      changeValueUnit,
      delectIds,
      selectItemFn,
      addPersonBox,
      handleClosePerson,
      closePersonbox,
      deptForm
    }


  },
}


</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 48%;
}
:global(.el-dialog__body) {
  padding: 0;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
  vertical-align: middle;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.content-box {
  width: 250px;
  height: 33px;
  padding: 5px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select {
  color: #eee;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
}

.handle {
  position: absolute;
  top: 17px;
  right: 20px;
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 10px;
}
</style>
